package android.mobile.peakgames.net.aspectjandroid.aspect;

import android.util.Log;
import android.widget.Button;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect public class LoggingAspect {
  private static final String TAG = LoggingAspect.class.getName();

  @Pointcut("execution(* android.view.View.OnClickListener.onClick(..))")
  public void onClickEntryPoint() {
  }

  @Pointcut("execution(* android.mobile.peakgames.net.aspectjandroid.AspectActivity.zAdd(..))")
  public void hookAdd() {
  }

  @Before("hookAdd()") public void onAddBefore(JoinPoint joinPoint) {
    Log.d(TAG, String.format("wta : %d__%d", joinPoint.getArgs()[0], joinPoint.getArgs()[1]));
    Log.d(TAG, "joinPoint.getThis():" + joinPoint.getThis());
  }

  @Before("execution(* android.mobile.peakgames.net.aspectjandroid.AspectActivity.foo(..))")
  public void logOpenGameDetail(JoinPoint joinPoint) {
    Log.d(TAG, String.format("openGameDetail()'s arg type=%s", joinPoint.getArgs()[0]));
  }

  @Around("execution(* android.mobile.peakgames.net.aspectjandroid.AspectActivity.zAdd(java.lang.Integer, java.lang.Integer))")
  public Object catchReturnValue(final ProceedingJoinPoint joinPoint) throws Throwable {
    try {
      Log.d(TAG,
          String.format("wta wanna : %d__%d", joinPoint.getArgs()[0], joinPoint.getArgs()[1]));
      Object proceed = joinPoint.proceed();
      Log.d(TAG, String.format("wta : result is: %s", proceed.toString()));
      return proceed;
    } catch (Throwable throwable) {
      throwable.printStackTrace();
      return null;
    }
  }

  /////////////////////////////////////////////////////////////////////////////////////////////////

  @Before("onClickEntryPoint()") public void onClickBefore(JoinPoint joinPoint) {
    Log.d(TAG, "Before Advice ==> Clicked on : " + ((Button) joinPoint.getArgs()[0]).getText());
  }

  @Around("onClickEntryPoint()") public void onClickAround(ProceedingJoinPoint joinPoint)
      throws Throwable {
    Log.d(TAG, "Around Advice ==> Clicked on : " + ((Button) joinPoint.getArgs()[0]).getText());

    joinPoint.proceed();
  }

  @After("onClickEntryPoint()") public void onClickAfter(JoinPoint joinPoint) {
    Log.d(TAG, "After Advice ==> Clicked on : " + ((Button) joinPoint.getArgs()[0]).getText());
  }

  @AfterReturning(pointcut = "onClickEntryPoint()") public void onClickAfterReturning() {
    Log.d(TAG, "AfterReturning Advice ==>");
  }
}
